import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as nunjucks from 'nunjucks';
import { AppModule } from './app.module';
import { join } from 'path';
import * as session from 'express-session';
import flash = require('connect-flash');
import morgan = require('morgan');
import * as passport from 'passport';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ConfigService } from './config/config.service';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  // 配置日志
  app.use(morgan('combined'));

  // 校验输入参数
  app.useGlobalPipes(new ValidationPipe());

  // swagger配置
  const options = new DocumentBuilder()
    .setTitle('fly cms example')
    .setDescription('The fly cms API description')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document);

  // nunjucks模板
  const env = nunjucks.configure(
    join(__dirname, '..', 'views'),
    {
      autoescape: true,
     throwOnUndefined: false,
      trimBlocks: false,
      lstripBlocks: false,
      watch: true,
      noCache: process.env.NODE_ENV === 'local' ? true : false,
      express: app,
    },
  );
  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setViewEngine('njk');

  const service = app.get(ConfigService);
  service.setRuntime('nunjucks', env);

  // 配置session
  app.use(
    session({
      secret: 'nest cats',
      resave: false,
      saveUninitialized: false,
    }),
  );

  // 配置passport
  app.use(passport.initialize());
  app.use(passport.session());

  // 配置flash
  app.use(flash());

  await app.listen(3000);
}
bootstrap();
